//
//  LookingTestingViewController.swift
//  E-CycleForShop
//
//  Created by enghou on 17/3/14.
//  Copyright © 2017年 xyxorigation. All rights reserved.
//

import UIKit

class LookingTestingViewController: BaseViewController {

    //需要上一个页面传递
    var screen_display : String = ""
    var touch_error : String = ""
    var price_range : String = ""
    
    var head : TestPhoneModelView?
    
    var screenFunc : ScreenFuncView?
    
    var mod : PhoneInfoModel?
    
    var decreaseItems : Array<DecreaseItemModel> = []
    
    var goods_id : Int = -1
    override func viewDidLoad() {
        super.viewDidLoad()
        self.naviHide = false
        self.title = "检测外观"
        self.defaultBackButton()
        configSubView()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    private func configSubView()->Void{
        
        head = TestPhoneModelView.init(frame: CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: YXDeviceWidth, height: 200 * YXHeightScale)))
        
        if mod != nil {
            head!.title = mod!.phone_model
        }
        
        head!.priceRange = price_range
        screenFunc = ScreenFuncView.init(frame: CGRect.init(origin: CGPoint.init(x: 10 * YXWidthScale, y: 10 * YXHeightScale), size: CGSize.init(width: YXDeviceWidth - 20 * YXWidthScale, height: 278 * YXHeightScale)))
        let scroll = UIScrollView.init(frame: CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: YXDeviceWidth, height: YXDeviceHeight - 140 * YXHeightScale - 64)))
        
        self.view.addSubview(scroll)
        scroll.backgroundColor = UIColor.colorWithHexString(hex: "ececec")
        scroll.addSubview(head!)
        let tray = UIView.init(frame: CGRect.init(origin: CGPoint.init(x: 0, y: 206 * YXHeightScale), size: CGSize.zero))
        tray.backgroundColor = UIColor.colorWithHexString(hex: "f3f3f5")
        scroll.addSubview(tray)
        screenFunc!.addHead(title: "外观")
        screenFunc!.addBlock(idx: 1, title: "1.边框外壳", titleArr: ["机身完好","机身变形/弯曲","外表磕碰磨损"], multiChoose: false, key: "border_shell")//与接口字段相同
        screenFunc!.addBlock(idx: 2, title: "2.屏幕外观", titleArr: ["屏幕完整","外屏破碎"], multiChoose: false, key: "screen_appearance")//与接口字段相同
        screenFunc!.addBlock(idx: 3, title: "3.维修拆机史", titleArr:["无维修","有维修"], multiChoose: false, key: "maintenance")//有无维修历史 与接口字段相同
        if self.decreaseItems.count > 0 {
            var array : Array<String> = []
            for item in decreaseItems {
                array.append(item.type)
            }
            screenFunc!.addBlock(title: "4.其他问题 (可多选,如无问题可直接点击立即评估)", titleArr: array, key: "problems", multiChoose: true,extra: false)
            screenFunc!.configFrame(origin: CGPoint.init(x: 10 * YXWidthScale, y: 10 * YXHeightScale), width: YXDeviceWidth - 20 * YXWidthScale)
        } else {
            screenFunc!.configFrame(origin: CGPoint.init(x: 10 * YXWidthScale, y: 10 * YXHeightScale), width: YXDeviceWidth - 20 * YXWidthScale)
        }
        tray.addSubview(screenFunc!)
        tray.frame = CGRect.init(origin: CGPoint.init(x: 0, y: 206 * YXHeightScale), size: CGSize.init(width: YXDeviceWidth, height: screenFunc!.bottom()))
        
        let base = UIView.init(frame: CGRect.init(x: 0, y: self.view.height() - 140 * YXHeightScale - 64, width: YXDeviceWidth, height: 140 * YXHeightScale))
        base.layer.borderColor = UIColor.colorWithHexString(hex: "f2f2f2").cgColor
        base.layer.borderWidth = YXHeightScale
        base.backgroundColor = UIColor.white
        self.view.addSubview(base)
        let estimate = UIButton.init(type: .system)
        estimate.setTitle("立即评估", for: .normal)
        estimate.backgroundColor = UIColor.black
        estimate.titleLabel?.font = UIFont.systemFont(ofSize: 36 * YXWidthScale)
        estimate.setTitleColor(UIColor.white, for: .normal)
        estimate.layer.cornerRadius = YXButtonCorner
        estimate.frame = CGRect.init(x: (YXDeviceWidth - 480 * YXWidthScale) / 2, y: (base.height() - 108 * YXHeightScale) / 2, width: 480 * YXWidthScale, height: 108 * YXHeightScale)
        estimate.addTarget(self, action: #selector(estimated), for: .touchUpInside)
        base.addSubview(estimate)
        scroll.contentSize = CGSize.init(width: 0, height: tray.bottom())
        self.automaticallyAdjustsScrollViewInsets = false
    }
    
    @objc func estimated() -> Void {
        if mod != nil && self.goods_id != -1{
            var param : Dictionary<String,String> = ["detection_id":String(mod!.id),"base_id":String(self.goods_id),"screen_show":screen_display,"touch_error":touch_error,"border_shell":"","screen_appearance":"","maintenance":""]
            let arr = screenFunc!.provideAllParam()
            for item in arr {
                if item.keys.contains("border_shell") {
                    let border = item["border_shell"] as! String
                    if border == "0" {
                        param["border_shell"] = "0"
                    }else if border == "1" {
                        param["border_shell"] = "1"
                    } else if border == "2"{
                        param["border_shell"] = "2"
                    }else{
                        commonAlertMsg(content: "请选择边框参数!")
                        return
                    }
                }
                if item.keys.contains("screen_appearance") {
                    let appearance = item["screen_appearance"] as! String
                    if appearance == "0" {
                        param["screen_appearance"] = "0"
                    }else if appearance == "1" {
                        param["screen_appearance"] = "1"
                    } else {
                        commonAlertMsg(content: "请选择屏幕参数!")
                        return
                    }
                }
                if item.keys.contains("maintenance") {
                    let maintain = item["maintenance"] as! String
                    if maintain == "0" {
                        param["maintenance"] = "0"
                    }else if maintain == "1" {
                        param["maintenance"] = "1"
                    } else {
                        commonAlertMsg(content: "请选择维修参数!")
                        return
                    }
                }
                if let array = item["problems"] as? Array<String> {
                    if array.count > 0{
                        var cntArr : Array<String> = []
                        for item in decreaseItems {
                            cntArr.append(item.type)
                        }
                        let problems = NumberStringMap.toString(array: array, contentArr: cntArr)
                        param["problems"] = problems
                    }
                }
            }
            self.beginAnim()
            Manager.shared().getPhoneFinalPrice(param: param, success: {(model) in
                if model.result == false {
                    self.commonAlertMsg(content: model.msg)
                    return
                } else {
                    if let dataDic = model.data as? Dictionary<String,Any>{
                        if let final = dataDic["finalMoney"] as? Int {
                            param["final_price"] = String(final)
                            let hall_id = DataCacher.shared().id()
                            param["business_hall_id"] = String(hall_id)
                            self.preUploadGoodsInfo(param: param, price: final)
                        }
                    }
                }
            }, fail: {(code) in
                self.endAnim()
                self.commonAlertMsg(content: YXNetWorkFail)
            })
        } else {
            commonAlertMsg(content: "尚未获取商品数据,请重试")
        }
    }
    
    func preUploadGoodsInfo(param : Dictionary<String,String>,price : Int) -> Void {
        Manager.shared().addCompletedOrder(param: param, success: {(mod) in
            self.endAnim()
            if let data = mod.data as? Dictionary<String,Int> {
                NotificationCenter.default.post(name: NSNotification.Name("addComplete"), object: nil)
                if let id = data["id"] {
                    let finalVC = FinalTestingViewController.init()
                    if self.mod != nil {
                        finalVC.model = self.mod
                    }
                    finalVC.id = id
                    finalVC.goods_id = self.goods_id
                    finalVC.price = price
                    finalVC.finalParam = param
                    self.navigationController?.pushViewController(finalVC, animated: true)
                }else {
                    self.commonAlertMsg(content: "获取订单失败!")
                }
            }
        }, fail: {(code) in
            self.endAnim()
            self.commonAlertMsg(content: YXNetWorkFail)
        })
    }
    
    
}
